<template>
  <view class="detail-container">
    <!-- 加载状态 -->
    <view v-if="isLoading && !isDataLoaded" class="loading-container">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view v-else-if="isDataLoaded && family.id" class="content-container">
      <view class="header">
        <view class="imgBox">
          <image src="https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/17fd89bd09124f3a82e3c9a844543d90.png" class="cover-img" />
          <view class="jzName">{{ family.familyName }}</view>
        </view>
        <view class="info-block">
          <view class="family-title">{{ family.familyName }}</view>
          <view class="family-meta">发起人：{{ family.inheritor || "暂无" }}</view>
          <view class="family-meta">入谱人数：{{ family.count || "--" }}</view>
          <view class="family-meta">创建日期：{{ family.createTime }}</view>
          <button
            v-if="getShowButton()"
            :class="['optBtn', getJoinButtonType(family)]"
            :disabled="isJoinButtonDisabled(family)"
            style="margin: 24rpx 0 0 0"
            @click="applyJoin()"
          >
            {{ getJoinButtonText(family) }}
          </button>
        </view>
      </view>
      <view style="height: 0; margin: 0; padding: 0"></view>
      <view class="desc-block">
        <ModuleList :joinStatus="family.joinStatus" :familyId="family.id"></ModuleList>
      </view>
    </view>

    <!-- 空状态 - 没有家谱数据 -->
    <view v-else class="no-family-message">
      <view class="book-cover">
        <view class="book-spine"></view>
        <view class="book-content">
          <view class="book-title">{{ family.familyName || "暂无家谱" }}</view>
          <view class="book-meta-group">
            <view class="book-meta">发起人：{{ family.inheritor || "暂无" }}</view>
            <view class="book-meta">入谱人数：{{ family.count || "--" }}</view>
            <view class="book-meta">创建日期：{{ family.createTime || "--" }}</view>
          </view>
          <view class="book-desc">{{ family.description || "暂无简介" }}</view>
        </view>
        <view v-if="getJoinButtonText(family) !== '审核中...'" class="action-button-group">
          <button
            class="action-button"
            :class="getJoinButtonType(family)"
            :disabled="isJoinButtonDisabled(family)"
            @click="joinFamily"
          >
            {{ getJoinButtonText(family) }}
          </button>
          <button class="action-button" @click="createFamily">创建家谱</button>
        </view>
        <view v-if="getJoinButtonText(family) === '审核中...'" class="pending-status-container">
          <button class="pending-status-button" type="warning" disabled>审核中</button>
          <view class="pending-status-desc">您的申请正在审核中，请耐心等待</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from "@/store/modules/user";
import FamilyAPI from "@/api/genealogy/family";
import ModuleList from "@/pages/genealogy/components/ModuleList.vue";

export default {
  name: "GenealogyDetail",
  components: {
    ModuleList,
  },
  data() {
    return {
      modules: [],
      family: {},
      familyId: null,
      userId: null,
      from: null, // 来源：myFamily表示从我的家谱进入
      hasPendingApplication: false, // 添加待审核状态标记
      isLoading: false, // 添加加载状态
      isDataLoaded: false, // 标记数据是否已加载
    };
  },
  onLoad(query) {
    this.userStore = useUserStore();

    if (query.from === "myFamily" && query.userId) {
      // 我的家谱模式
      this.from = "myFamily";
      this.userId = query.userId;
      this.getMyFamilyDetail();
      // 设置页面标题
      uni.setNavigationBarTitle({
        title: "我的家谱",
      });
    } else if (query.familyId) {
      // 普通家谱详情模式
      this.familyId = query.familyId;
      this.getFamilyDetail(query.familyId);
    } else {
      // 如果没有参数，提示错误
      uni.showToast({
        title: "参数错误：缺少必要参数",
        icon: "none",
      });
      this.isDataLoaded = true; // 标记加载完成，显示空状态
    }
  },
  mounted() {
    // 不再使用本地存储数据
  },
  activated() {
    // 组件被激活时，根据模式刷新数据
    if (this.isLoading) return;

    if (this.from === "myFamily" && this.userId) {
      this.getMyFamilyDetail();
    } else if (this.familyId) {
      this.getFamilyDetail(this.familyId);
    }
  },
  methods: {
    handleModuleClick(module) {},
    getShowButton() {
      return (
        this.family.hasJoined !== 1 || // 未加入
        this.family.joinStatus != null // 或 joinStatus 有值（包括 0）
      );
    },

    // 检查是否存在待审核状态的家谱
    checkPendingApplication() {
      // 现在只依赖接口返回的数据，不再使用本地存储
      // 根据接口返回的joinStatus判断申请状态
      if (this.family && this.family.joinStatus === 0) {
        this.hasPendingApplication = true;
      } else {
        this.hasPendingApplication = false;
      }
    },
    getFamilyDetail(val) {
      // 避免重复调用
      if (this.isLoading) return;

      this.isLoading = true;
      const userStore = useUserStore();
      const userInfo = userStore.userInfo;

      const params = {
        familyId: val,
        userId: userInfo?.userId || "",
        pageNum: 1,
        pageSize: 10,
        familyName: "",
      };

      FamilyAPI.getDetailCheck(params)
        .then((res) => {
          console.log("getDetailCheck res", res);
          if (res) {
            const apiData = res;
            // 映射API数据到本地数据结构
            this.family = {
              id: apiData.id,
              familyName: apiData.familyName,
              inheritor: apiData.nickname || "暂无", // 使用nickname作为发起人
              count: apiData.nums || "--", // 使用nums作为入谱人数
              createTime: apiData.createTime,
              hasJoined: apiData.hasJoined || 0,
              joinStatus: apiData.joinStatus,
              activedStatus: apiData.activedStatus || 0,
              // 保留原始API数据的所有字段
              ...apiData,
            };
            this.isDataLoaded = true; // 标记数据已加载

            // 检查是否存在待审核状态的家谱
            this.checkPendingApplication();
          } else {
            // 没有数据的情况
            uni.showToast({
              title: "未找到家谱信息",
              icon: "none",
            });
          }
        })
        .catch((err) => {
          console.error("获取家谱详情失败", err);
          uni.showToast({
            title: "获取家谱详情失败",
            icon: "none",
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    getMyFamilyDetail() {
      // 避免重复调用
      if (this.isLoading) return;

      this.isLoading = true;
      const userStore = useUserStore();
      const userInfo = userStore.userInfo;

      const params = {
        userId: this.userId || userInfo?.userId || "",
        pageNum: 1,
        pageSize: 10,
        familyName: "",
      };

      FamilyAPI.getMyDetail(params)
        .then((res) => {
          console.log("getMyDetail res", res);
          if (res && res.list && res.list.length > 0) {
            const apiData = res.list[0];
            // 映射API数据到本地数据结构
            this.family = {
              id: apiData.id,
              familyName: apiData.familyName,
              inheritor: apiData.nickname || "暂无", // 使用nickname作为发起人
              count: apiData.nums || "--", // 使用nums作为入谱人数
              createTime: apiData.createTime,
              hasJoined: apiData.hasJoined || 0,
              joinStatus: apiData.joinStatus,
              activedStatus: apiData.activedStatus || 0,
              // 保留原始API数据的所有字段
              ...apiData,
            };
            this.isDataLoaded = true; // 标记数据已加载

            // 检查是否存在待审核状态的家谱
            this.checkPendingApplication();
          }
        })
        .catch((err) => {
          console.error("获取我的家谱详情失败", err);
          uni.showToast({
            title: "获取我的家谱详情失败",
            icon: "none",
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },
    applyJoin() {
      const buttonText = this.getJoinButtonText(this.family);
      if (buttonText === "查看家谱") {
        // 查看家谱
        uni.navigateTo({
          url: `/pages/genealogy/person/index?familyId=${this.family.id}`,
        });
      } else if (buttonText === "被拒绝") {
        // 被拒绝状态，重新选择家谱
        uni.navigateTo({
          url: `/pages/genealogy/index?fromDetail=true&reapply=true`,
        });
      } else if (buttonText === "审核中") {
        // 审核中状态，显示提示信息
        uni.showModal({
          title: "申请审核中",
          content: "您的加入申请正在审核中，请耐心等待。",
          showCancel: false,
          confirmText: "知道了",
        });
      } else {
        // 申请加入
        const userStore = useUserStore();
        const userInfo = userStore.userInfo;
        if (this.family.activedStatus === 1 || (userInfo && userInfo.userId == 2)) {
          uni.navigateTo({
            url: `/pages/genealogy/person/index?familyId=${this.family.id}`,
          });
        } else {
          uni.navigateTo({
            url: `/pages/genealogy/join?familyId=${this.family.id}`,
          });
        }
      }
    },

    // 添加没有家谱时的方法
    createFamily() {
      // 跳转到创建家谱页面，传递参数标识从详情页面跳转并显示创建表单
      uni.navigateTo({
        url: `/pages/genealogy/index?fromDetail=true&showCreateForm=true`,
      });
    },

    joinFamily() {
      const buttonText = this.getJoinButtonText(this.family);

      if (buttonText === "查看家谱") {
        // 查看家谱
        uni.navigateTo({
          url: `/pages/genealogy/person/index`,
        });
      } else if (buttonText === "被拒绝") {
        // 被拒绝状态，重新申请加入
        uni.navigateTo({
          url: `/pages/genealogy/index?fromDetail=true&reapply=true`,
        });
      } else if (buttonText === "审核中") {
        // 审核中状态，显示提示信息
        uni.showModal({
          title: "申请审核中",
          content: "您的加入申请正在审核中，请耐心等待。",
          showCancel: false,
          confirmText: "知道了",
        });
      } else {
        // 加入家谱
        const userStore = useUserStore();
        const userInfo = userStore.userInfo;
        uni.navigateTo({
          url: `/pages/genealogy/index?fromDetail=true&city=${userInfo?.mergerName || ""}`,
        });
      }
    },
    getJoinButtonText(row) {
      if (row.hasJoined === 1) {
        if (row.activedStatus === 1) return "查看家谱";
        if (row.joinStatus === 1) return "等待入谱";
        if (row.joinStatus === 0) return "审核中";
        if (row.joinStatus === 2) return "被拒绝";
        return "申请加入";
      } else {
        if (row.activedStatus === 1) return "查看家谱";
        if (row.joinStatus === 1) return "等待入谱";
        if (row.joinStatus === 0) return "审核中";
        if (row.joinStatus === 2) return "被拒绝";
        return "申请加入";
      }
    },
    getJoinButtonType(row) {
      if (!row) row = this.family;
      if (row.activedStatus === 1) return "btn-success";
      if (row.joinStatus === 1) return "btn-info";
      if (row.joinStatus === 0) return "btn-warning";
      if (row.joinStatus === 2) return "btn-danger";
      return "apply-btn";
    },
    isJoinButtonDisabled(row) {
      const text = this.getJoinButtonText(row);
      // 只有"申请加入""查看家谱""被拒绝""审核中"可点击，其它禁用
      return !["申请加入", "查看家谱", "被拒绝", "审核中"].includes(text);
    },

    // 微信分享功能 - 分享给朋友
    onShareAppMessage() {
      // 根据不同的模式返回不同的分享配置
      if (this.family && this.family.id) {
        return {
          title: this.family.familyName || "家族文化传承",
          path: `/pages/genealogy/detail?familyId=${this.family.id}`,
          // imageUrl: "", // 可选，分享图
        };
      } else if (this.from === "myFamily" && this.userId) {
        return {
          title: "我的家谱",
          path: `/pages/genealogy/detail?from=myFamily&userId=${this.userId}`,
          // imageUrl: "", // 可选，分享图
        };
      }
      // 默认分享配置
      return {
        title: "家族文化传承",
        path: "/pages/genealogy/detail",
        // imageUrl: "", // 可选，分享图
      };
    },

    // 微信分享功能 - 分享到朋友圈
    onShareTimeline() {
      // 根据不同的模式返回不同的分享配置
      if (this.family && this.family.id) {
        return {
          title: this.family.familyName || "家族文化传承",
          query: `familyId=${this.family.id}`,
          // imageUrl: "", // 可选，分享图
        };
      } else if (this.from === "myFamily" && this.userId) {
        return {
          title: "我的家谱",
          query: `from=myFamily&userId=${this.userId}`,
          // imageUrl: "", // 可选，分享图
        };
      }
      // 默认分享配置
      return {
        title: "家族文化传承",
        query: "",
        // imageUrl: "", // 可选，分享图
      };
    },
  },
};
</script>

<style scoped>
/* 添加样式 */
.desc-block {
  background: #fff;
  border-radius: 20rpx;
  margin: 30rpx 30rpx 0 30rpx;
  padding: 30rpx 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(191, 163, 107, 0.08);
}

.module-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.module-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 31%;
  cursor: pointer;
  padding: 10px 0;
  background: #f5f5f5;
}

.module-icon {
  height: 80rpx;
  border-radius: 12rpx;
  object-fit: cover;
  margin-bottom: 10rpx;
  font-size: 80rpx;
  color: #00147b;
}

.module-title {
  font-size: 26rpx;
  color: #333;
  text-align: center;
}

.detail-container {
  /* background: #f5e9da; */
  padding: 40rpx 0 0 0;
  height: 100%;
}
.header {
  display: flex;
  background: #fff;
  border-radius: 24rpx;
  margin: 40rpx 30rpx 20rpx 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(191, 163, 107, 0.1);
  padding: 30rpx 20rpx;
  align-items: center;
}
.imgBox {
  position: relative;
}
.jzName {
  position: absolute;
  left: 0.4rem;
  top: 1.7rem;
  width: 0.58rem;
  height: 2.3rem;
  writing-mode: vertical-rl;
  text-orientation: mixed;
  overflow: hidden;
  white-space: pre-line;
  font-size: 0.4rem;
  overflow-y: hidden;
  font-weight: bold;
  text-align: center;
}
.cover-img {
  width: 180rpx;
  height: 220rpx;
  border-radius: 12rpx;
  object-fit: cover;
  background: #f5e9da;
  margin-right: 30rpx;
}
.info-block {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}
.family-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}
.family-meta {
  font-size: 26rpx;
  color: #666;
}
.apply-btn {
  background: #e95d2a;
  color: #fff;
  border-radius: 12rpx;
  font-size: 26rpx;
  font-weight: bold;
  padding: 10rpx 36rpx;
  margin: 14rpx 0 0 0;
  box-shadow: 0 2rpx 8rpx rgba(233, 93, 42, 0.1);
  display: inline-block;
  letter-spacing: 2rpx;
  min-width: 120rpx;
  width: auto; /* 新增，让宽度自适应内容 */
}
.optBtn {
  margin-top: 0 !important;
}
.btn-success {
  background: #67c23a;
  color: #fff;
}
.btn-info {
  background: #909399;
  color: #fff;
}
.btn-warning {
  background: #e6a23c !important;
  color: #fff !important;
}
.btn-danger {
  background: #f56c6c;
  color: #fff;
}
.desc-block {
  background: #fff;
  border-radius: 20rpx;
  margin: 30rpx 30rpx 0 30rpx;
  padding: 30rpx 24rpx;
  box-shadow: 0 2rpx 8rpx rgba(191, 163, 107, 0.08);
}
.desc-title {
  font-size: 28rpx;
  color: #bfa36b;
  font-weight: bold;
  margin-bottom: 10rpx;
}
.desc-content {
  font-size: 26rpx;
  color: #444;
  line-height: 1.7;
  text-align: justify;
  text-indent: 2em;
}

.section-block {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #eee;
}

.section-title {
  font-size: 28rpx;
  color: #bfa36b;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.section-content {
  font-size: 26rpx;
  color: #444;
  line-height: 1.7;
  text-align: justify;
  text-indent: 2em;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  /* background: #f5e9da; */
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #165dff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #666;
}

/* 空状态样式 */
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5e9da;
}

.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.5;
}

.empty-text {
  margin-top: 20rpx;
  font-size: 28rpx;
  color: #999;
}

.content-container {
  min-height: 100vh;
}

/* 没有家谱时的样式 */
.no-family-message {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 50px;
}

.action-button-group {
  width: 13rem;
  margin: 0 auto;
  display: flex;
  justify-content: space-around;
  position: absolute;
  bottom: 10px;
  z-index: 10;
}

.action-button {
  background: #e95d2a;
  color: #fff;
  border-radius: 12rpx;
  font-size: 26rpx;
  font-weight: bold;
  padding: 10rpx 36rpx;
  margin: 10rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(233, 93, 42, 0.1);
  width: 200rpx;
  text-align: center;
}

.pending-status-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20rpx;
  padding: 20rpx 0;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(191, 163, 107, 0.08);
  position: absolute;
  bottom: 4px;
}

.pending-status-button {
  background: #e6a23c;
  color: #fff;
  border-radius: 12rpx;
  font-size: 26rpx;
  font-weight: bold;
  padding: 10rpx 36rpx;
  margin: 10rpx 0;
  box-shadow: 0 2rpx 8rpx rgba(230, 162, 60, 0.1);
  width: 200rpx;
  text-align: center;
}

.pending-status-desc {
  font-size: 24rpx;
  color: #666;
  margin-top: 10rpx;
  text-align: center;
}

.book-cover {
  width: 14rem;
  height: 19rem;
  background:
    repeating-linear-gradient(135deg, rgba(200, 190, 170, 0.08) 0 2px, transparent 2px 12px),
    linear-gradient(135deg, #f3f3f3 80%, #e0d6c3 100%),
    repeating-linear-gradient(0deg, rgba(255, 255, 255, 0.12) 0 1px, transparent 1px 8px);
  border-radius: 18rpx;
  box-shadow:
    0 8rpx 32rpx rgba(191, 163, 107, 0.13),
    0 2rpx 8rpx #e0d6c3;
  position: relative;
  margin-bottom: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.book-spine {
  position: absolute;
  left: 0;
  top: 0;
  width: 18rpx;
  height: 100%;
  background: linear-gradient(90deg, #d1c3a3 60%, #e0d6c3 100%);
  border-top-left-radius: 18rpx;
  border-bottom-left-radius: 18rpx;
  box-shadow: 2rpx 0 8rpx #e0d6c3;
  z-index: 1;
}

.book-content {
  position: relative;
  z-index: 2;
  width: 92%;
  height: 92%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 2.2rem 1.2rem 1.2rem 2.2rem;
  box-sizing: border-box;
  background: transparent;
}

.book-title {
  font-size: 1.5rem;
  color: #bfa36b;
  font-weight: bold;
  letter-spacing: 2rpx;
  text-align: left;
  margin-bottom: 1.2rem;
  user-select: none;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.book-meta-group {
  width: 100%;
  margin-bottom: 1.2rem;
}

.book-meta {
  font-size: 0.8rem;
  color: #8c7b5a;
  margin-bottom: 0.3rem;
  text-align: left;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-desc {
  font-size: 0.8rem;
  color: #a89c7a;
  margin-top: 0.5rem;
  text-align: left;
  width: 100%;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
  background: transparent;
}
</style>
